package com.zbkj.crmebadmin.controller;


import com.alibaba.excel.EasyExcel;
import com.zbkj.common.request.SystemAdminLoginRequest;
import com.zbkj.common.response.CommonResult;
import com.zbkj.common.response.MenusResponse;
import com.zbkj.common.response.SystemLoginResponse;
import com.zbkj.common.utils.CrmebUtil;
import com.zbkj.crmebadmin.service.AdminLoginService;
import com.zbkj.crmebadmin.vo.AdminLoginExcelVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("api/admin")
@Api(tags = "管理端登录服务")
public class AdminLoginController {

    @Autowired
    private AdminLoginService adminLoginService;


    @ApiOperation(value="PC登录")
    @PostMapping(value = "/login", produces = "application/json")
    public CommonResult<SystemLoginResponse> SystemAdminLogin(@RequestBody @Validated SystemAdminLoginRequest systemAdminLoginRequest, HttpServletRequest request){
        String ip = CrmebUtil.getClientIp(request);
        //        log.error(bindingResult.getFieldError().getDefaultMessage());
        SystemLoginResponse systemLoginResponse = new SystemLoginResponse();
         systemLoginResponse.setId(123);
         return CommonResult.success(systemLoginResponse);
    }

    /**
     * 获取管理员可访问目录
     */
//    @PreAuthorize("hasAuthority('admin:login:menus')")
    @ApiOperation(value = "获取管理员可访问目录")
    @RequestMapping(value = "/getMenus", method = RequestMethod.GET)
    public CommonResult<List<MenusResponse>> getMenus() {
        return CommonResult.success(adminLoginService.getMenus());
    }

    @ApiOperation(value = "导出管理员登录记录")
    @GetMapping("/exportLoginRecord")
    public void exportLoginRecord(HttpServletResponse response) throws IOException {
        // 设置响应头
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("管理员登录记录", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");

        // 模拟数据，实际项目中应该从数据库获取
        List<AdminLoginExcelVo> list = new ArrayList<>();
        AdminLoginExcelVo vo = new AdminLoginExcelVo();
        vo.setId(1);
        vo.setAccount("admin");
        vo.setRealName("管理员");
        vo.setLastLoginTime("2024-03-20 10:00:00");
        vo.setLastLoginIp("127.0.0.1");
        list.add(vo);

        // 导出Excel
        EasyExcel.write(response.getOutputStream(), AdminLoginExcelVo.class)
                .sheet("管理员登录记录")
                .doWrite(list);
    }

}
